﻿using System;
using System.Xml;
using Microsoft.Crm.Sdk;
using TTprotons.Crm.JavascriptAudit.Common;

namespace TTprotons.Crm.JavascriptAudit
{
    public class RetrievePrePublishCustomizationPlugin : IPlugin
    {
        #region IPlugin Members

        public void Execute(IPluginExecutionContext context)
        {
            var publishedDate = DateTime.Now;

            // Setup the ContextHelper and CrmService.
            var contextHelper = new ContextHelper(context);
            var crmService = contextHelper.CrmService;

            if (!context.InputParameters.Contains(Constants.ParameterXml))
                return;

            try
            {
                var parameterXml = context.InputParameters[Constants.ParameterXml].ToString();
                var parser = new ParameterXmlParser(parameterXml);
                var entityName = parser.EntityName;

                // Export the customization for the Primary Entity.
                var exportManager = new CustomizationExportManager();
                var exportResult = exportManager.Export(crmService, entityName);

                // Store it in the SharedVariables so that it is accessible for other plugins.
                if (context.SharedVariables.Contains(Constants.PrePublishCustomization))
                    context.SharedVariables[Constants.PrePublishCustomization] = exportResult.ExportCompressedXml;
                else
                    context.SharedVariables.Properties.Add(new PropertyBagEntry(Constants.PrePublishCustomization, exportResult.ExportCompressedXml));

                if (context.SharedVariables.Contains(Constants.PublishedOn))
                    context.SharedVariables[Constants.PublishedOn] = publishedDate;
                else
                    context.SharedVariables.Properties.Add(new PropertyBagEntry(Constants.PublishedOn, publishedDate));
            }
            catch (Exception)
            { }
        }

        #endregion
    }
}